<template>
	<view>
    <view class="search-box">
      <uni-search-bar @input="input" :radius="100" cancelButton="none"></uni-search-bar>
    </view>
    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResults.length !== 0">
      <view class="sugg-item" v-for="(item, i) in searchResults" :key="i" @click="gotoDetail(item.goods_id)">
        <view class="goods-name">{{item.goods_name}}</view>
        <uni-icons type="arrowright" size="16"></uni-icons>
      </view>
    </view>
    <!-- 搜索历史 -->
    <view class="history-box" v-else v-show="historyList.length !== 0">
      <!-- 标题区域 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="delectSearch"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <uni-tag :text="item" v-for="(item, i) in historyList" :key="i" @click="gotoGoodsList(item)"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
	export default {
		data() {
			return {
				timer: null,  // 防抖延时器的 timerId
         kw: '',       // 搜索关键词
         searchResults: [],  // 搜索结果列表
         historyList:JSON.parse(uni.getStorageSync('SEARCHLIST')) || [],  // 搜索关键词的历史记录
         searchValue: '123123'
			};
		},
    methods: {
      input(e) {
        clearTimeout(this.timer)  // 清除 timer 对应的延时器
        this.timer = setTimeout(() => {
          this.kw = e.value  // 如果 500 毫秒内，没有触发新的输入事件，则为搜索关键词赋值
          this.getSearchList()  // 出发延时器，查询搜索建议列表
        }, 500)
      },
      // 搜索建议列表
      async getSearchList() {
        if(this.kw.trim()==='') return this.searchResults=[]
         const { data: res } = await uni.$http.get('/api/public/v1/goods/qsearch', { query: this.kw })  // 发起请求，获取搜索建议列表
         if (res.meta.status !== 200) return uni.$showMsg()
          this.searchResults = res.message
      },
      gotoDetail(goods_id){
        uni.navigateTo({
          // 指定详情页面的 URL 地址，并传递 goods_id 参数
          url: `/subpkg/goods_deatil/goods_deatil?goods_id=${goods_id}`
        })
        this.saveSearchHistory()  // 调用 saveSearchHistory() 方法保存搜索关键词
      },
      saveSearchHistory(){
        this.historyList.unshift(this.kw)  // 直接把搜索关键词 push 到 historyList 数组中
        this.historyList=this.historyList.filter(function (item, index, arr) {return arr.indexOf(item) === index;})
        uni.setStorageSync('SEARCHLIST',JSON.stringify(this.historyList))
      },
      delectSearch(){
          uni.setStorageSync('SEARCHLIST', '[]') // 清空本地存储中记录的搜索历史
      },
      // 点击跳转到商品列表页面
      gotoGoodsList(value) {
        uni.navigateTo({
            url: '/subpkg/goods_list/goods_list?query=' + value
          })
      }
    }
	}
</script>

<style lang="scss">
.search-box {
  position: sticky;
  top: 0;
  z-index: 999;
}
.sugg-list{
  padding: 0 5px;
  .sugg-item{
    font-size: 12px;
    padding: 13px 0;
    border-bottom: 1px solid #efefef;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .goods-name{
      white-space: nowrap;
      overflow: hidden;
       text-overflow: ellipsis; // 文本溢出后，使用 ... 代替
       margin-right: 3px;
    }
  }
}
.history-box {
  padding: 0 5px;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    .uni-tag {
      margin-top: 5px;
      margin-right: 5px;
    }
  }
}
</style>
